package demo04

/**
 * @author xiaoZhao
 * @date 2022/6/29
 * @describe
 */
object Test12_MyWhile {
  def main(args: Array[String]): Unit = {
    var n = 10
    // 1.常规while循环
    while (n >= 1) {
      println(n)
      n -= 1
    }

    // 2.自定义函数实现while功能
    // 用闭包实现函数，将代码块传入
    def myWhile(condition: => Boolean): (=> Unit) => Unit = {
      // 内层函数需要递归调用 参数为循环体
      def doLoop(op: => Unit): Unit = {
        if (condition) {
          op
          myWhile(condition)(op)
        }
      }

      doLoop _
    }

    n = 10
    myWhile(n >= 1) {
      println(n)
      n -= 1
    }

  // 3.简化
    def myWhile2(condition: => Boolean): (=> Unit) => Unit = {
      // 内层函数需要递归调用 参数为循环体
      op=>{
        if (condition) {
          op
          myWhile2(condition)(op)
        }
      }
    }


    // 4.柯里化
    def myWhile3(condition: => Boolean)(op: Unit): Unit={
      if (condition) {
        op
        myWhile3(condition)(op)
      }
    }
    n = 10
    myWhile3(n >= 1) {
      println(n)
      n -= 1
    }
  }
}
